package com.miao.teacher.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

public class Utils {
	private static final String TAG = "Utils";

	public static int getVersionCode(Context context) {
		int versionCode = 0;
		// ��ȡ����汾�ţ���ӦAndroidManifest.xml��android:versionCode
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					"com.yishuodian.dianping", 0).versionCode;
			Log.i(TAG, "versionCode = " + versionCode);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}
	public static String md5(String text) {
		if (text == null)
			return null;
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(text.getBytes());
			byte[] digest = md.digest();
			for (int i = 0; i < digest.length; i++) {
				String digit = Integer.toHexString(0xFF & digest[i]);
				if (digit.length() < 2) {
					digit = "0" + digit;
				}
				hexString.append(digit);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hexString.toString();// 32 digits
		// return hexString.toString().substring(8,24);//16 digits
	}

	public static String md5(byte[] btext) {
		if (btext == null)
			return null;
		// String text;
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(btext);
			byte[] digest = md.digest();
			for (int i = 0; i < digest.length; i++) {
				String digit = Integer.toHexString(0xFF & digest[i]);
				if (digit.length() < 2) {
					digit = "0" + digit;
				}
				hexString.append(digit);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hexString.toString();// 32 digits
		// return hexString.toString().substring(8,24);//16 digits
	}

	// public static boolean ckeckSum(byte[] massage, int readLeng) {
	// if (readLeng <= 32 || massage.length < readLeng) {
	// if (readLeng > 0)
	// Log.i(TAG,
	// "massage = "
	// + new String(massage).substring(0, readLeng));
	// else
	// Log.i(TAG, "readLeng <= 0");
	// return false;
	// }
	// byte[] head = new byte[readLeng - 32];
	// byte[] sum = new byte[32];
	// Log.d(TAG, "head = " + head);
	// Log.d(TAG, "sum  = " + sum);
	// System.arraycopy(massage, 0, head, 0, head.length);
	// System.arraycopy(massage, head.length, sum, 0, sum.length);
	// String headSum = md5(head);
	// String realSum = new String(sum);
	// Log.v(TAG, "headSum = " + headSum);
	// Log.v(TAG, "realSum = " + realSum);
	// boolean equal = headSum.equalsIgnoreCase(realSum);
	// Log.i(TAG, "ckeckSum returns " + equal);
	// return equal;
	// }

	public static byte[] file2Byte(File file) {
		boolean failed = false;
		byte[] buffer = new byte[(int) file.length()];
		InputStream ios = null;
		try {
			ios = new FileInputStream(file);
			if (ios.read(buffer) == -1) {
				throw new IOException(
						"EOF reached while trying to read the whole file");
			}
		} catch (FileNotFoundException e) {
			failed = true;
			e.printStackTrace();
		} catch (IOException e) {
			failed = true;
			e.printStackTrace();
		} finally {
			try {
				if (ios != null)
					ios.close();
			} catch (IOException e) {
				failed = true;
			}
		}
		if (failed) {
			return null;
		} else {
			return buffer;
		}
	}

	public static String encodeBase64File(File file) {
		byte[] buffer = file2Byte(file);
		if (buffer == null) {
			Log.w(TAG, "can't read file to buffer.");
			return null;
		}
		return Base64.encodeToString(buffer, Base64.NO_WRAP);

	}

	public static void showProgress(Dialog dialog, boolean show) {
		if (dialog == null)
			return;
		if (show) {
			if (!dialog.isShowing())
				dialog.show();
		} else {
			dialog.dismiss();
		}
	}

	public static void deleteFolder(File file) {
		if (file.isFile()) {
			file.delete();
			return;
		}

		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				deleteFolder(childFiles[i]);
			}
			file.delete();
		}
	}

	/* Checks if external storage is available for read and write */
	public static boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	// private static String getRandomString(int length) { // length��ʾ����ַ�ĳ���
	// String base =
	// "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	// Random random = new Random();
	// StringBuffer sb = new StringBuffer();
	// for (int i = 0; i < length; i++) {
	// int number = random.nextInt(base.length());
	// sb.append(base.charAt(number));
	// }
	// return sb.toString();
	// }

	public static String getTimeStamp(long diff) {
		long serverTime = ((new Date().getTime()) + diff) / 1000;
		return String.valueOf(serverTime);
	}

	// get adapted SD card path
	public static File getExternalStorageDirectory() {
		return Environment.getExternalStorageDirectory();
	}

	/**
	 * JPush Utilities
	 */
	public static final String PREFS_NAME = "JPUSH_EXAMPLE";
	public static final String PREFS_DAYS = "JPUSH_EXAMPLE_DAYS";
	public static final String PREFS_START_TIME = "PREFS_START_TIME";
	public static final String PREFS_END_TIME = "PREFS_END_TIME";
	public static final String KEY_APP_KEY = "JPUSH_APPKEY";

	public static boolean isEmpty(String s) {
		if (null == s)
			return true;
		if (s.length() == 0)
			return true;
		if (s.trim().length() == 0)
			return true;
		return false;
	}

	// У��Tag Alias ֻ��������,Ӣ����ĸ������
	public static boolean isValidTagAndAlias(String s) {
		Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
		Matcher m = p.matcher(s);
		return m.matches();
	}

	// ȡ��AppKey
	public static String getAppKey(Context context) {
		Bundle metaData = null;
		String appKey = null;
		try {
			ApplicationInfo ai = context.getPackageManager()
					.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA);
			if (null != ai)
				metaData = ai.metaData;
			if (null != metaData) {
				appKey = metaData.getString(KEY_APP_KEY);
				if ((null == appKey) || appKey.length() != 24) {
					appKey = null;
				}
			}
		} catch (NameNotFoundException e) {

		}
		return appKey;
	}

	// ȡ�ð汾��
	public static String GetVersion(Context context) {
		try {
			PackageInfo manager = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return manager.versionName;
		} catch (NameNotFoundException e) {
			return "Unknown";
		}
	}

	public static void showToast(final String toast, final Context context) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				Looper.prepare();
				Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		}).start();
	}

	public static boolean isConnected(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = conn.getActiveNetworkInfo();
		return (info != null && info.isConnected());
	}

	public static String getImei(Context context, String imei) {
		try {
			TelephonyManager telephonyManager = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			imei = telephonyManager.getDeviceId();
		} catch (Exception e) {
			Log.e(Utils.class.getSimpleName(), e.getMessage());
		}
		return imei;
	}
}
